package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName ExcelDictDTOListener.java
 * @Description TODO 监听器
 * @createTime 2022年02月14日 16:17:00
 */
@Slf4j
@NoArgsConstructor //无参构造函数
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    @Resource
    private DictMapper dictMapper;

    ArrayList<ExcelDictDTO> list = new ArrayList<>();
    private static final int BATCH_COUNT = 5;

    //有参构造函数
    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", data);
        //调用mapper层的save方法
        // 将数据存入数据列表
        list.add(data);

        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    private void saveData() {
        log.info("{} 条数据存储到数据库......", list.size());
        //调用mapper层的save方法

        dictMapper.insertBatch(list);

        log.info("{} 条数据存储到数据库成功", list.size());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("数据解析完成!");

    }
}
